package com.tedu.openmedical.medicalsystem.base.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.tedu.openmedical.medicalsystem.user.pojo.dto.UserLoginParam;
import lombok.Data;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Data
public class JwtUtils {
    /**
     * 加密的秘钥,相当于服务器私钥,一定保管好,不能泄露
     */
    private static final String SECRET  = "secret";
    /**
     * token的有效时间,不需要自己验证失效,当失效后,会自动抛出异常
     */
    private static final long EXPIRE = 30 * 60 * 1000;

    public static String createToken(UserLoginParam userLoginParam) throws UnsupportedEncodingException {

        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        return JWT.create()
                .withHeader(map)
                .withClaim("userName", userLoginParam.getUserName())
                .withClaim("password", userLoginParam.getPassword())
                .withClaim("loginType", userLoginParam.getLoginType())
                .withClaim("phone", userLoginParam.getPhone())
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRE))
                .withIssuedAt(new Date())
                .sign(Algorithm.HMAC256(SECRET ));
    }

    public static DecodedJWT verify(String token) throws UnsupportedEncodingException {
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }
}
